package com.tom.architect02.zframework.viewpager.lazy;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.tom.architect02.R;
import com.tom.architect02.zframework.viewpager.lazy.fragment.Fragment1;
import com.tom.architect02.zframework.viewpager.lazy.fragment.Fragment2;
import com.tom.architect02.zframework.viewpager.lazy.fragment.Fragment3;
import com.tom.architect02.zframework.viewpager.lazy.fragment.Fragment4;
import com.tom.architect02.zframework.viewpager.lazy.fragment.Fragment6;

import java.util.ArrayList;

public class SecondActivity extends AppCompatActivity {

    private ViewPager viewPager;

    private TabLayout tabLayout;

    private ArrayList<LazyFragment> fragments;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        initView();
    }

    private void initView() {
        fragments = new ArrayList<>();
        viewPager = findViewById(R.id.activity_second_viewPager);
        tabLayout = findViewById(R.id.activity_tabLayout);
//        for (int i = 0; i < 10; i++) {
//            fragments.add(fragment1);
//        }

        fragments.add(new Fragment1());
        fragments.add(new Fragment2());
        fragments.add(new Fragment3());
        fragments.add(new Fragment4());
        fragments.add(new Fragment6());
        //他会真正销毁我们的fragment，只保存状态
//        FragmentStatePagerAdapter
        //mActive  这个数组 会造成oom

        //他不会真正销毁
        FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
//                Fragment1 fragment1 = new Fragment1();
//                Bundle bundle = new Bundle();
//                bundle.putString("fragment", "" + position);
//                fragment1.setArguments(bundle);
//                fragments.add(fragment1);
//                return fragment1;
                return fragments.get(position);
            }
            @Override
            public int getCount() {
                return fragments.size();
            }
        };
        viewPager.setAdapter(fragmentPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            tabLayout.getTabAt(i).setText("Tab " + i);
        }
        viewPager.setOffscreenPageLimit(fragments.size());
    }
}
